import { createI18n } from "vue-i18n";
import type { App } from "vue";
import { setHtmlPageLang } from "./helper";
import type { I18n, I18nOptions } from "vue-i18n";
import env from "/@/base/env";
import * as dayjs from "dayjs";

export let i18n: ReturnType<typeof createI18n>;

async function createI18nOptions(): Promise<I18nOptions> {
  const locale = env.lang;
  const defaultLocal = await import(`./lang/${locale}.ts`);
  dayjs.locale(defaultLocal.default?.dayjsLocaleName ?? "zh-cn");
  const message = defaultLocal.default?.message ?? {};
  setHtmlPageLang(locale);

  return {
    legacy: false,
    locale,
    fallbackLocale: "zh_CN",
    messages: {
      [locale]: message,
    },
    sync: true, //If you don’t want to inherit locale from global scope, you need to set sync of i18n component option to false.
    silentTranslationWarn: true, // true - warning off
    missingWarn: false,
    silentFallbackWarn: true,
  };
}

// setup i18n instance with glob
export async function setupI18n(app: App) {
  const options = await createI18nOptions();
  i18n = createI18n(options) as I18n;
  app.use(i18n);
}
